<template>
  <div class="app-container">
    
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col
          v-for="column in props.columns.filter(item=>item.search) "
          :key="column.prop"
          :span="5"
        >
          <el-form-item :label="column.label" >
            <component :is="column.formate ? column.formate() : ElInput" v-model="searchForm[column.prop]" />
          </el-form-item>
        </el-col>
        <!-- 搜索按钮 -->
        
      </el-row>
      <div style="text-align: right">
        <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
      </div>
    </el-form>

    <!-- 表格主体 -->
    <el-table :data="initData" border style="width: 100%" v-loading="loading">
      <el-table-column
        v-for="column in props.columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :type="column.type"
        :width="column.width"
        :fixed="column.fixed"
      >
        <template #default="{ row }">
          <div v-if="column.h">
            <component :is="column.h(row)" />
          </div>
          <div v-else>
            {{ row[column.prop] ?? "--" }}
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="isPagination"
      background
      layout="prev, pager, next"
      :total="pagination.total"
      class=""
      @current-change="handlePageChange"
    />
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted } from "vue";
import { ElInput, ElSelect, ElOption } from "element-plus";

/** 定义传递数据 */
const props = defineProps({
  columns: {
    type: Array,
    required: true,
  },
  isPagination: {
    type: Boolean,
    default: false,
  },
});

/** 自定义事件 */
const emits = defineEmits(["request"]);

// 搜索表单模型
const searchForm = ref({});

// 初始化搜索表单
props.columns.forEach((col) => {
  if (col.search) {
    searchForm.value[col.prop] = "";
  }
});

// 分页信息
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

const loading = ref(false);

// 搜索方法
const onSearch = () => {
  // 构造参数对象
  const params = {
    pagination: pagination.value,
    searchForm: searchForm.value
  };
  loading.value = true

  // 触发请求，并传入参数
  emits("request", {
    ...params,
    callback: (result) => {
      initData.value = result.data;
      pagination.value.total = result.total;
      loading.value = false;
    }
  });
};

// 重置搜索条件
const onReset = () => {
  props.columns.forEach((col) => {
    if (col.search) {
      searchForm.value[col.prop] = "";
    }
  });

  // 可选：触发一次搜索
  onSearch();
};

// 初始加载数据
const initData = ref([]);
onMounted(() => {
  onSearch();
});
</script>


<style lang="scss" scoped>
.demo-form-inline{
  margin-bottom: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
  justify-content: right;
  
}
</style>